<template>
  
  <div>
    
  <el-table
    :data="pagedTableData"
    style="width: 100%">
    <el-table-column v-for="(item) in Object.keys(tableHeadData)" :key="item.tnub"
      :label="tableHeadData[item]"
      width="180">
      <template slot-scope="scope">
        <i class="el-icon-time"></i>
        <span style="margin-left: 10px">{{ scope.row[item] }}</span>
      </template>
    </el-table-column>
    
    <el-table-column label="操作">
      <template slot-scope="scope">
        <el-button
          size="mini"
          @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
        <el-button
          
          size="mini"
          type="danger"
          @click="handleDelete(scope.$index, scope.row) ">删除</el-button>
      </template>
    </el-table-column>
  </el-table>
    
    <div class="my-paging">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 30, 40]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="computedTotal">
        </el-pagination>
</div>

  </div>
</template>

<script>
import axios from 'axios'



export default {
    data(){
        return{
            identity: 'student',
            submitData:{},

            //表头数据
            tableHeadData:{
              tnub: '老师编号',
              username:'用户名',
              password:'密码',
              tname:'姓名',
              college: '所属院校',
              phone: '电话',
              
            },

            //编辑数据
            message: [],

            labelPosition: 'right',
            formLabelAlign: {
              name: '',
              region: '',
              type: ''
            },
            tableData: [
              
            ],
          currentPage: 1,
          pageSize: 10,
          

        }
    },
    computed:{
      computedTotal(){
        return this.tableData.length
      },
      pagedTableData() {
      const startIndex = (this.currentPage - 1) * this.pageSize;
      const endIndex = startIndex + this.pageSize;
      return this.tableData.slice(startIndex, endIndex);
      }
    },
    components:{
        

    },
    methods:{
        handleEdit(index, row) {
            console.log(index, row);
            this.message = []
            const h = this.$createElement;
          console.log(row.name);
          //要求：表头数据的key和tableData里的每一个数据对象的key相同
          Object.keys(this.tableHeadData).forEach(element => {
            const h1 = h('div', {style:{
                fontSize: '14px',
                marginTop: '8px',
                width: '100%',
                height: '30px',
                textAlign: 'center',
                lineHeight: '30px',
            }
              
            }, [
            h('div', {
              style:{
                width: 'auto',
                height: '30px',
                display: 'inline-block'
              }
            }, `${this.tableHeadData[element]}`),
            h('input', {
              attrs: {
                value: row[element]?row[element]:""
              },
              style:{
                marginLeft: '8px',
                float: 'right'
              },
              on: {
                input: (event)=> {
                  // 在这里可以获取到输入框的值
                  let currentKey = element
                  let value = event.target.value
                  
                  this.submitData[currentKey] = value
                  
                  
                  console.log(event.target.value);
                }
            }
            }),
            
           
          ]);
            this.message.push(h1)
          });

           

        this.$msgbox({
          title: '编辑',
          message:  h('div', null,this.message) ,
          showCancelButton: true,
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          beforeClose: (action, instance, done) => {
            if (action === 'confirm') {
              instance.confirmButtonLoading = true;
              instance.confirmButtonText = '执行中...';
              //todo
              setTimeout(() => {
                done();
                setTimeout(() => {
                  instance.confirmButtonLoading = false;
                }, 300);
              }, 2000);
            } else {
              done();
            }
          }
        }).then(action => {
          // 处理编辑按钮更改数据库
          if (action === 'confirm') {
            const msg = this.handleConfirmAction(this.submitData,row); // 处理点击确定按钮后的逻辑
            this.$message({
              type: 'info',
              message: msg
            })
          } else {
            this.$message({
              type: 'info',
              message: '已取消修改'
            })
          }
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消修改'
          });          
        })
            
            
        },
        handleDelete(index, row) {
          this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
          }).then(() => {
            console.log(row.username);
          // 删除逻辑，需要 提交一个username
          axios.get(`/prod-api/teacher/del?username=${row.username}`)
          .then(response =>{
                  console.log(row.username);
                  console.log(response);
                  if(response.data.code === 0){
                    this.$message({
                        type: 'success',
                        message: '删除成功!'
                      });
                      this.pagedTableData.splice(index, 1);
                      this.tableData = this.tableData.filter(item => item.tnub!==row.tnub)
                  }
                })
                .catch(error => {
                    this.$router.push({name:'error', params:{error:error}})
                })
          console.log(456);
          //todo,将信息编号传递到这，根据编号删除tableData的数据即可
          //并且发送请求将编号传递到后端，进行逻辑删除

        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
            console.log(index,row);
            
            console.log(this.pagedTableData);
        },
        handleConfirmAction(submitData,row){
          // 更改老师某个信息操作, 提交所有老师信息
          let obj
          obj = Object.assign({},row,submitData)
          console.log(obj);
          axios.put(`/prod-api/teacher/upData`,obj)
                .then(response =>{
                  if(response.data.code === 0)
                    return response.data.msg
                }).catch(error=>{
                   this.$router.push({name:'error', query:{error:error}})
                })
          location.reload(true)
        },
        handleSizeChange(val) {
          this.pageSize = val;
        },
        handleCurrentChange(val) {
          this.currentPage = val;
        }
    },
    created(){
      
      axios.post('/prod-api/teacher/All')
                .then(response => {//TODO
                    console.log(response.data);
                    this.tableData = response.data
                    })
                .catch(error => {
                    this.$router.push({name:'error' , params:{error:error}})

                })
    }
}

</script>

<style>
.my-paging{
  text-align: center;
  margin-top: 20px;
}

</style>